﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace com.tanlingyun.helper
{
    public class CookieHelper
    {
        /// <summary>
        /// 添加Cookie
        /// </summary>
        /// <param name="name">Cookie名</param>
        /// <param name="value">Cookie值</param>
        public static void Add(string name,string value)
        {
            Add(name,value,false);
        }
        /// <summary>
        /// 添加Cookie
        /// </summary>
        /// <param name="name">Cookie名</param>
        /// <param name="value">Cookie值</param>
        /// <param name="HttpOnly">为true的时候js不可以读取</param>
        public static void Add(string name,string value,bool HttpOnly = false)
        {
            if (HttpContext.Current == null || HttpContext.Current.Response == null || HttpContext.Current.Response.Cookies == null)
                return;
            HttpCookie cookie = new HttpCookie(name, value);
            //cookie.Domain = "77sucai.top";
            cookie.HttpOnly = HttpOnly;
            //cookie.Expires = DateTime.Now.AddDays(7);
            HttpContext.Current.Response.Cookies.Add(cookie);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <param name="ExpiresTime"></param>
        /// <param name="HttpOnly"></param>
        public static void Add(string name, string value, DateTime ExpiresTime,bool HttpOnly=false)
        {
            if (HttpContext.Current == null || HttpContext.Current.Response == null || HttpContext.Current.Response.Cookies == null)
                return;
            HttpCookie cookie = new HttpCookie(name, value);
            //cookie.Domain = "77sucai.top";
            //cookie.Domain = HttpContext.Current.Request.UserHostName;
            cookie.Expires = ExpiresTime;
            cookie.HttpOnly = HttpOnly;
            HttpContext.Current.Response.Cookies.Add(cookie);
        }
        /// <summary>
        /// 获取Cookie的值
        /// </summary>
        /// <param name="name">cookie名</param>
        /// <returns></returns>
        public static object GetValue(string name)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(name);
            if (cookie == null) return null;
            return cookie.Value;
        }
        /// <summary>
        /// 删除制定名称的Cookie
        /// </summary>
        /// <param name="name">Cookie名称</param>
        public static void Remove(string name)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[name];
            if (cookie != null)
            {
                cookie.Expires = DateTime.Now.AddYears(-1);
                HttpContext.Current.Response.Cookies.Add(cookie);
                HttpContext.Current.Request.Cookies.Remove(name);
            }
        }
    }
}
